package com.plum.filter;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.plum.core.PlumInit;
import com.plum.core.PlumSecurity;
import com.plum.model.AjaxRet;
import com.plum.session.HttpContext;

public class PlumFilter extends PlumInit implements Filter {
	protected FilterConfig filterConfig;
	
	public FilterConfig getFilterConfig() {
		return filterConfig;
	}

	protected void setFilterConfig(FilterConfig filterConfig) {
		this.filterConfig = filterConfig;
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		setFilterConfig(filterConfig);
		setCtx(filterConfig.getServletContext().getContextPath());
		//String iniPath = filterConfig.getInitParameter(PLUM_INI_PATH);
		String iniPath = PLUM_INI_PATH;
		try {
			
			initProp(iniPath);
			initData();
			initRealm(REALM_CLASS);
			PlumSecurity.getRealm().init();
			if(!isAfterStartInit()) {
				PlumSecurity.initAllowExtMapAndRoleExtMap();
			}
		} catch (Exception e) {
			if (e instanceof ServletException) {
				throw (ServletException) e;
			} else {
				throw new ServletException(e);
			}
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse rep = (HttpServletResponse) response;
		HttpSession session = req.getSession();
		HttpContext.begin(req, rep);
		String url = req.getRequestURI();
		Object obj = session.getAttribute(SESSION_USER_KEY);
		boolean isAllow = PlumSecurity.isAllow(url);
		// obj为空代表未登录
		if (obj == null) {
			if (isAllow) {
				// 让目标资源执行
				chain.doFilter(request, response);
			} else {
				if (isAjax(req)) { // 判断是否为ajax访问
					AjaxRet ret = AjaxRet.fail("errorCode", "-100").set("errorMsg", "当前未登录，未获得访问权限");
					AjaxReturn(rep, ret);
				} else {
					rep.sendRedirect(DEFAULT_LOGIN_URL);
				}
			}
		} else {
			if (isAllow) {
				chain.doFilter(request, response);
			} else {
				boolean isRole = PlumSecurity.hasRole(url);
				if (isRole) {
					chain.doFilter(request, response);
				} else {
					if (isAjax(req)) { // 判断是否为ajax访问
						AjaxRet ret = AjaxRet.fail("errorCode", "-99").set("errorMsg", "权限不足");
						AjaxReturn(rep, ret);
					} else {
						rep.sendRedirect(DEFAULT_UNAUTHORIZED_URL);
					}
				}
			}
		}
	}

	@Override
	public void destroy() {
		// HttpContext.get().end();
	}

}
